--[[

]]--

local Timer = class("Timer")
-- Timer.__index = Timer

local function _nothing_() end

function Timer:ctor()

end

function Timer:update(dt)
	local to_remove = {}
	for handle, delay in pairs(self.functions) do
		delay = delay - dt
		if delay <= 0 then
			to_remove[#to_remove+1] = handle
		end
		self.functions[handle] = delay
		handle.func(dt, delay)
	end
	for _,handle in ipairs(to_remove) do
		self.functions[handle] = nil
		handle.after(handle.after)
	end
end

function Timer:do_for(delay, func, after)
	local handle = {func = func, after = after or _nothing_}
	self.functions[handle] = delay
	return handle
end

function Timer:add(delay, func)
	return self:do_for(delay, _nothing_, func)
end

function Timer:addPeriodic(delay, func, count)
	local count, handle = count or math.huge -- exploit below: math.huge - 1 = math.huge

	handle = self:add(delay, function(f)
		if func(func) == false then return end
		count = count - 1
		if count > 0 then
			self.functions[handle] = delay
		end
	end)
	return handle
end

function Timer:cancel(handle)
	self.functions[handle] = nil
end

function Timer:clear()
	self.functions = {}
end


return Timer
